package com.bwie.auth.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bwie.auth.feign.AuthFegin;
import com.bwie.auth.service.AuthService;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.User;
import com.bwie.common.domain.request.UserVO;
import com.bwie.common.domain.response.UserResponse;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    private AuthFegin authFegin;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private HttpServletRequest request;


    /**
     * 登录
     */
    @Override
    public Result<UserResponse> login(UserVO userVO) {
        String userName = userVO.getUserName();
        String userPwd = userVO.getUserPwd();
        if(StringUtils.isAnyBlank(userName,userPwd)){
            return Result.error("用户名或密码错误");
        }

        Result<User> login = authFegin.login(userName);
        User user = login.getData();
//        if(user==null){
//            return Result.error("用户名不能为空");
//        }

        HashMap<String, Object> claims = new HashMap<>();
        String userkey = UUID.randomUUID().toString();
        claims.put(JwtConstants.USER_KEY,userkey);
        String token = JwtUtils.createToken(claims);

        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY+userkey,JSONObject.toJSONString(user),30, TimeUnit.MINUTES);
        UserResponse userResponse = new UserResponse();
        userResponse.setToken(token);
        userResponse.setDefittime("30MIN");
        return Result.success(userResponse,"登录成功");
    }

    /**
     * 获取token
     */
    @Override
    public User getInfo() {
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        String userJSONstr = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        User user = JSONObject.parseObject(userJSONstr, User.class);
        return user;
    }
}
